package com.snailhd.common.util.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class ParserParamUtil {

	private static final String APPLICATION_JSON = "application/json";

	private static final String JSON_REQUEST_BODY = "JSON_REQUEST_BODY";

	public static <T> T getParamFromRequest2Obj(HttpServletRequest request,Class<T> clazz) {
		String jsonBody = getParamFromRequest2Str(request);
		return JSON.parseObject(jsonBody,clazz);
	}

	public static JSONObject getParamFromRequest2JSONObj(HttpServletRequest request) {
		String jsonBody = getParamFromRequest2Str(request);
		return JSON.parseObject(jsonBody);
	}

	public static String getParamFromRequest2Str(HttpServletRequest request) {
		String type = request.getContentType();
		String jsonBody = null;
		if (APPLICATION_JSON.equals(type)) {
			jsonBody = getParamFromRequestBody(request);
		}else{
			jsonBody= getParamFromRequestFrom(request);
		}
		return jsonBody;
	}

	public static String getParamFromRequestFrom(HttpServletRequest request){
		Map param = new HashMap();
		Enumeration enumStr = request.getParameterNames();
		while (enumStr.hasMoreElements()) {
			String paramName = (String) enumStr.nextElement();
			String paramValue = request.getParameter(paramName);
			param.put(paramName, paramValue);
		}
		if (param.isEmpty()) {
			return null;
		}
		return JSON.toJSONString(param);
	}



	public static String getParamFromRequestBody(HttpServletRequest request){
		String jsonBody = (String) request.getAttribute(JSON_REQUEST_BODY);
		if (jsonBody == null) {
			try {
				jsonBody = IOUtils.toString(request.getInputStream(),"utf-8");
				request.setAttribute(JSON_REQUEST_BODY, jsonBody);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		return jsonBody;
	}
}
